import {
  SortableContext,
  verticalListSortingStrategy
} from '@dnd-kit/sortable'


import {
  type DragEndEvent,
  MouseSensor,
  useSensor,
  useSensors,
  DndContext,
  closestCenter
 }  from '@dnd-kit/core'


import type { JSX } from 'react'
import { useStore } from '@/store'


type PropsType ={
  children:JSX.Element | JSX.Element[],
  items: Array<{id:string,[key:string]:any}> 
  onDragEnd: (oldIndex:number,newIndex:number) => void
  isDrag?: boolean
}

export default function SortableContainer(props: PropsType) {
  const {setSelectedId} = useStore()

  const { children, items, onDragEnd,isDrag } = props

  const sensors = useSensors(
    useSensor(MouseSensor,{
      activationConstraint: {
        distance: 8
      }
    })
  )

  const handleDragEnd = (event: DragEndEvent) => {
    if(!isDrag) return 
    const { active, over } = event
    if(over == null) return 
    if(active.id !== over.id ) {
      const oldIndex = items.findIndex(item => item.fe_id === active.id)
      const newIndex = items.findIndex(item => item.fe_id === over.id)
      onDragEnd(oldIndex,newIndex)
      setSelectedId(active.id.toString())
    }
   
  }

  return (
    <DndContext
      sensors={sensors}
      collisionDetection={closestCenter}
      onDragEnd={handleDragEnd}
    >
      <SortableContext items={items} strategy={verticalListSortingStrategy}>
        {children}
      </SortableContext>

    </DndContext>
  )
}
